﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace T.FAS.Runtime.MF.Activities.Extensions
{
    public static class JArrayExtensions
    {/// <summary>
     /// 将 JArray 转换为保留原始数组结构的 object 数组
     /// </summary>
     /// <param name="jArray">要转换的 JArray</param>
     /// <returns>保留数组结构的 object 数组</returns>
        public static object[] ToStructuredObjectArray(this JArray jArray)
        {
            var result = new List<object>();
            foreach (var token in jArray)
            {
                result.Add(ConvertJToken(token));
            }
            return result.ToArray();
        }

        /// <summary>
        /// 递归转换 JToken 到适当的 C# 类型
        /// </summary>
        public static object ConvertJToken(JToken token)
        {
            if (token == null) return null;
            
            switch (token.Type)
            {
                case JTokenType.Array:
                    // 保留数组结构：转换为 object[]
                    return ((JArray)token).ToStructuredObjectArray();

                case JTokenType.Object:
                    // 将对象转换为 Dictionary<string, object>
                    return ConvertJObject((JObject)token);

                case JTokenType.Integer:
                    return token.Value<int>();

                case JTokenType.Float:
                    return token.Value<double>();

                case JTokenType.String:
                    return token.Value<string>();

                case JTokenType.Boolean:
                    return token.Value<bool>();

                case JTokenType.Null:
                    return null;

                case JTokenType.Date:
                    return token.Value<DateTime>();

                case JTokenType.Guid:
                    return token.Value<Guid>();

                case JTokenType.Uri:
                    return token.Value<Uri>();

                case JTokenType.TimeSpan:
                    return token.Value<TimeSpan>();

                default:
                    // 回退处理
                    return token.ToString();
            }
        }

        /// <summary>
        /// 将 JObject 转换为 Dictionary<string, object>
        /// </summary>
        private static Dictionary<string, object> ConvertJObject(JObject jObject)
        {
            var dict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);

            foreach (var property in jObject.Properties())
            {
                dict[property.Name] = ConvertJToken(property.Value);
            }

            return dict;
        }
    }
}
